<template>
  <view class="container">
    <view class="amount-section">
      <text class="label">支付金额</text>
      <text class="amount">¥{{ amount }}</text>
    </view>

    <view class="payment-section">
      <view class="title">支付方式</view>
      <view class="payment-item" @tap="selectPayment('wxpay')">
        <view class="left">
          <image
            src="/static/images/wxpay.png"
            mode="aspectFit"
            class="icon"
          ></image>
          <text>微信支付</text>
        </view>
        <uni-icons
          :type="paymentType === 'wxpay' ? 'checkbox-filled' : 'circle'"
          size="20"
          color="#ff4444"
        ></uni-icons>
      </view>
    </view>

    <!-- 调试信息显示 -->
    <view class="debug-section" v-if="debugInfo">
      <view class="debug-title">调试信息</view>
      <textarea class="debug-content" :value="debugInfo" readonly></textarea>
    </view>

    <button class="submit-btn" @tap="submitPay">确认支付</button>
    <button class="debug-btn" @tap="testApiCall">测试API调用</button>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { orderService } from "@/services/order";
import { payService } from "@/services/pay";

const orderId = ref("");
const amount = ref(0);
const paymentType = ref("wxpay");
const debugInfo = ref("");

// 页面加载
onLoad((options) => {
  orderId.value = options.orderId;
  amount.value = parseFloat(options.amount || 0);
});

// 选择支付方式
const selectPayment = (type) => {
  paymentType.value = type;
};

// 提交支付
const submitPay = async () => {
  console.log('=== 开始支付流程 ===');
  
  try {
    uni.showLoading({
      title: '处理中...'
    });
    
    console.log('1. 开始获取订单信息，orderId:', orderId.value);
    
    // 先获取订单信息以获取orderNo
    const orderRes = await orderService.getOrderDetail(orderId.value);
    if (!orderRes.success) {
      throw new Error('获取订单信息失败');
    }
    
    const orderNo = orderRes.data.orderNo;
    console.log('2. 获取订单信息成功，orderNo:', orderNo);
    
    // 调用支付接口获取支付参数
    console.log('3. 开始调用支付接口，参数:', {
      orderNo: orderNo,
      amount: amount.value * 100,
      total_fee: amount.value * 100,
      description: `订单${orderNo}支付`,
      paymentMethod: paymentType.value
    });
    
    const payRes = await payService.payOrder(orderNo, {
      amount: amount.value * 100, // 转换为分
      total_fee: amount.value * 100,
      description: `订单${orderNo}支付`,
      paymentMethod: paymentType.value
    });

    console.log('4. 支付接口调用完成，完整响应:', JSON.stringify(payRes, null, 2));

    // 根据实际的响应结构判断是否成功
    // 后端可能返回 code: 0 表示成功，但 success: false
    const isSuccess = payRes.code === 0 || payRes.success === true;
    const paymentData = payRes.data;

    console.log('5. 支付成功判断:', {
      原始code: payRes.code,
      原始success: payRes.success, 
      判断结果isSuccess: isSuccess,
      是否有数据hasData: !!paymentData,
      数据类型: typeof paymentData,
      数据内容: paymentData
    });

    if (!isSuccess) {
      console.error('支付判断失败，isSuccess为false');
      throw new Error(payRes.message || '创建支付失败');
    }
    
    if (!paymentData) {
      console.error('支付数据为空');
      throw new Error('支付数据获取失败');
    }

    console.log('6. 通过成功判断，隐藏加载框');
    uni.hideLoading();

    // 详细记录支付参数
    console.log('7. 支付参数详情检查:', {
      timeStamp: paymentData.timeStamp,
      timeStamp类型: typeof paymentData.timeStamp,
      nonceStr: paymentData.nonceStr,
      nonceStr类型: typeof paymentData.nonceStr,
      package: paymentData.package,
      package类型: typeof paymentData.package,
      signType: paymentData.signType,
      signType类型: typeof paymentData.signType,
      paySign: paymentData.paySign,
      paySign类型: typeof paymentData.paySign,
      完整数据: paymentData
    });

    // 检查支付参数是否完整
    const missingParams = [];
    if (!paymentData.timeStamp) missingParams.push('timeStamp');
    if (!paymentData.nonceStr) missingParams.push('nonceStr');
    if (!paymentData.package) missingParams.push('package');
    if (!paymentData.paySign) missingParams.push('paySign');
    
    if (missingParams.length > 0) {
      console.error('支付参数不完整，缺少:', missingParams);
      console.error('完整支付数据:', paymentData);
      throw new Error(`支付参数不完整，缺少: ${missingParams.join(', ')}`);
    }

    console.log('8. 支付参数验证通过，准备调用微信支付SDK...');

    // 调用微信支付SDK
    try {
      console.log('9. 开始调用 uni.requestPayment，参数:', {
        timeStamp: paymentData.timeStamp,
        nonceStr: paymentData.nonceStr,
        package: paymentData.package,
        signType: paymentData.signType || 'MD5',
        paySign: paymentData.paySign,
      });
      
      await uni.requestPayment({
        timeStamp: paymentData.timeStamp,
        nonceStr: paymentData.nonceStr,
        package: paymentData.package,
        signType: paymentData.signType || 'MD5',
        paySign: paymentData.paySign,
        success: (res) => {
          console.log('10. 微信支付成功回调:', res);
          uni.showToast({
            title: "支付成功",
            icon: "success",
          });
          
          // 支付成功后轮询支付状态
          pollPaymentStatus(orderId.value);
        },
        fail: (err) => {
          console.error("微信支付失败回调:", err);
          
          if (err.errMsg && err.errMsg.includes('cancel')) {
            console.log('用户取消支付');
            uni.showToast({
              title: "支付已取消",
              icon: "none",
            });
          } else {
            console.log('支付调用失败');
            uni.showToast({
              title: "支付失败",
              icon: "none",
            });
          }
          
          // 跳转到订单详情页面查看状态
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/order/detail?orderId=${orderId.value}`,
            });
          }, 1500);
        },
      });
      
      console.log('uni.requestPayment 调用已发起');
      
    } catch (paymentError) {
      console.error("调用 uni.requestPayment 异常:", paymentError);
      uni.showToast({
        title: "支付调用失败",
        icon: "none",
      });
      
      // 跳转到订单详情页面
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/order/detail?orderId=${orderId.value}`,
        });
      }, 1500);
    }
    
  } catch (error) {
    console.error("=== 支付流程异常 ===");
    console.error("错误详情:", error);
    console.error("错误消息:", error.message);
    console.error("错误堆栈:", error.stack);
    
    uni.hideLoading();
    uni.showToast({
      title: error.message || "支付处理失败",
      icon: "none",
    });
  }
  
  console.log('=== 支付流程结束 ===');
};

// 轮询支付状态
const pollPaymentStatus = async (orderId, maxAttempts = 10) => {
  let attempts = 0;
  
  const checkStatus = async () => {
    try {
      const res = await payService.queryPayment(orderId);
      
      if (res.success) {
        const status = res.data.payStatus;
        
        if (status === 'SUCCESS') {
          // 支付成功，跳转到订单详情
          uni.redirectTo({
            url: `/pages/order/detail?orderId=${orderId}`,
          });
          return;
        } else if (status === 'FAILED') {
          // 支付失败
          uni.showToast({
            title: "支付失败",
            icon: "none",
          });
          
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/order/detail?orderId=${orderId}`,
            });
          }, 1500);
          return;
        }
      }
      
      // 继续轮询
      if (attempts < maxAttempts) {
        attempts++;
        setTimeout(checkStatus, 2000); // 2秒后重试
      } else {
        // 超时，跳转到订单详情页面让用户手动查看
        uni.redirectTo({
          url: `/pages/order/detail?orderId=${orderId}`,
        });
      }
    } catch (error) {
      console.error('查询支付状态失败:', error);
      // 查询失败，跳转到订单详情页面
      uni.redirectTo({
        url: `/pages/order/detail?orderId=${orderId}`,
      });
    }
  };
  
  // 开始轮询
  checkStatus();
};

// 测试API调用
const testApiCall = async () => {
  try {
    const res = await payService.testApi();
    debugInfo.value = JSON.stringify(res, null, 2);
    uni.showToast({
      title: "测试API调用成功",
      icon: "success",
    });
  } catch (error) {
    console.error("测试API调用失败:", error);
    uni.showToast({
      title: error.message || "测试API调用失败",
      icon: "none",
    });
  }
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20rpx;
}

.amount-section {
  background-color: #fff;
  padding: 40rpx;
  text-align: center;
  margin-bottom: 20rpx;

  .label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: block;
  }

  .amount {
    font-size: 60rpx;
    color: #ff4444;
    font-weight: bold;
  }
}

.payment-section {
  background-color: #fff;
  padding: 30rpx;

  .title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
  }

  .payment-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;

    .left {
      display: flex;
      align-items: center;

      .icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 20rpx;
      }

      text {
        font-size: 28rpx;
      }
    }
  }
}

.debug-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .debug-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
  }

  .debug-content {
    width: 100%;
    height: 200rpx;
    border: 1rpx solid #ccc;
    padding: 10rpx;
  }
}

.submit-btn {
  position: fixed;
  left: 30rpx;
  right: 30rpx;
  bottom: 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #ff4444;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.debug-btn {
  position: fixed;
  left: 30rpx;
  right: 30rpx;
  bottom: 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #333;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin-left: 20rpx;
}
</style>
